﻿using UnityEngine;
using System.Collections;
namespace net {
	public class NetMain : MonoBehaviour {
		public Texture2D img;
		public static int assetCount = 0;
		public static int life = -1;	// 剩余生命数
		// 复活位置
		public Vector3 rebornPos = new Vector3 (9, 1, 0);
		int genCD = 15;
		Vector3[] serverGen = new Vector3[2];
		Vector3[] clientGen = new Vector3[2];
		bool genLock = false;
		bool InitOK = false;
		public GameObject myBase;
		public GameObject enemyBase;
		 float gameStartTime;
		//public ArrayList bases = new ArrayList 	();
		int[,] map = new int[6,13]{
			{0,0,3,0,19,7,1,5,19,0,20,0,0},
			{0,0,0,0,0,8,10,6,0,0,0,0,0},
			{0,0,21,0,18,18,18,18,0,0,21,0,0},
			{0,21,0,21,18,0,18,18,0,21,0,21,0},
			{0,0,21,0,18,18,18,18,0,21,0,0,0},
			{0,4,4,0,0,0,0,0,0,0,4,0,0}
		};

		GUIStyle style;

		int lastSec = 0;
		int nowSec = 0;

		NetPlayerState state = null;
		void Awake(){
			// 非移动设备隐藏摇杆
			if (Application.platform != RuntimePlatform.Android) {
				GameObject[] objs = GameObject.FindGameObjectsWithTag("TOUCH_ONLY");
				foreach (GameObject obj in objs) {
					Destroy(obj);
				}
			}
			if(Network.peerType == NetworkPeerType.Client){
				Network.minimumAllocatableViewIDs = 700;
			}
		}

		// Use this for initialization
			void Start () {
			//PlayerPrefs.DeleteAll ();
		// Network.isMessageQueueRunning = true;
			print("sendrate="+Network.sendRate);
			Network.sendRate = 5;

			// 重置静态变量
			assetCount = 0;
		
			Config cfg = new Config ();

			style = new GUIStyle ();
			style.fontSize = 18;
			style.normal.textColor = new Color32(255, 0, 0, 128);
			style.fontStyle = FontStyle.Bold;
			style.alignment = TextAnchor.MiddleLeft;

			serverGen[0] = new Vector3(9,1,0);
			serverGen[1] = new Vector3(17,1,0);

			clientGen[0] = new Vector3(9,25,0);
			clientGen[1] = new Vector3(17,25,0);

			// 播放音频
			AudioSource audioSource = GetComponent<AudioSource> ();
			audioSource.clip = Resources.Load("mp3/play") as AudioClip;
			audioSource.Play ();
			
			if(Network.peerType == NetworkPeerType.Server){

				//获取地图数据
				string strData = PlayerPrefs.GetString ("edit_map");
				
				//改变map数组，如果没有数据则表示使用默认地图
				if(strData!= null){
					// 字符串转数组
					string[] tmpArr1 = strData.Split (new char[]{';'}, System.StringSplitOptions.RemoveEmptyEntries);
					string[] tmpArr2;
					for (int i = 0; i < tmpArr1.Length; i++) {
						tmpArr2 = tmpArr1[i].Split(new char[]{','}, System.StringSplitOptions.RemoveEmptyEntries);
						for (int j = 0; j < tmpArr2.Length; j++) {
							map[i, j] = int.Parse(tmpArr2[j]);
						}
					}
				}

				// 绘制地图块
				for (int i = 0; i < 6; i++) {
					for (int j = 0; j < 13; j++) {
						
						Network.Instantiate (Resources.Load("prefab/" + cfg.codeToName(map[i, j])),
						                     new Vector3 ((j + 1) * 2 - 1, (i + 1) * 2 - 1, 0),
						                     Quaternion.identity,0
						                     );
						
					}
				}
				//添加坦克
				NewTank(true,cfg);


				//为中间加一条砖墙
				for(int i = 0;i<13;i++){
					Network.Instantiate( Resources.Load("prefab/"+cfg.codeToName(21)),
					                     new Vector3((i+1)*2-1,13,0),
					                     Quaternion.identity,0);   

				}
				// 绘制一圈河流
				Object river = Resources.Load ("prefab/iron");
				for (int i = 0; i < 13; i++) {
					// 上边
					Network.Instantiate (river,
					                     new Vector3 ((i + 1) * 2 - 1, 27, 0),
					                     Quaternion.identity,0
					                     );
					// 下边
					Network.Instantiate (river,
					                     new Vector3 ((i + 1) * 2 - 1, -1, 0),
					                     Quaternion.identity,0
					                     );
					// 左边
					Network.Instantiate (river,
					                     new Vector3 (-1, (i + 1) * 2 - 1, 0),
					                     Quaternion.identity,0
					                     );
					// 右边
					Network.Instantiate (river,
					                     new Vector3 (27, (i + 1) * 2 - 1, 0),
					                     Quaternion.identity,0
					                     );
				}
			}
			else if(Network.peerType == NetworkPeerType.Client){

				//改变摄像机的位置和角度
					float x = gameObject.transform.position.x ;
					float y = 18.7f;
					transform.rotation = Quaternion.Euler(new Vector3(0,0,180));
					transform.position = new Vector3(x,y,transform.position.z);

				//获取地图数据
				string strData = PlayerPrefs.GetString ("edit_map");
				int[,] temp = new int[6,13];

				//改变map数组，如果没有数据则表示使用默认地图
				if(strData!= null){
					// 字符串转数组
					string[] tmpArr1 = strData.Split (new char[]{';'}, System.StringSplitOptions.RemoveEmptyEntries);
					string[] tmpArr2;
					for (int i = 0; i < tmpArr1.Length; i++) {
						tmpArr2 = tmpArr1[i].Split(new char[]{','}, System.StringSplitOptions.RemoveEmptyEntries);
						for (int j = 0; j < tmpArr2.Length; j++) {
							map[i, j] = int.Parse(tmpArr2[j]);
						}
					}
				}
					
				string printstring = "";
				//旋转地图
				for(int i=0;i<6;i++){
					for(int j=0;j<13;j++){
						temp[i,j] = map[5-i,12-j];

					}
				}
					
				//绘制地图
				for(int i=7;i<13;i++){
					for(int j=0;j<13;j++){
						Network.Instantiate (Resources.Load("prefab/" + cfg.codeToName(temp[i-7, j])),
						                     new Vector3 ((j + 1) * 2 - 1, (i + 1) * 2 - 1, 0),
						                     Quaternion.Euler(0,0,180),0
						                     );
				
					}
				}
				NewTank(false,cfg);
			}

			//记录游戏开始时间
			gameStartTime = Time.time;
		}
		
		Object NewTank(bool isServer,Config cfg){
			
			Vector3 bornPosition;
			
			if(isServer){
				bornPosition=new Vector3(9,1,0) ;
			}
			else{
				bornPosition=new Vector3(17,25,0) ;	
			}

			//寻找可以出生的地点
			GameObject[] borns = GameObject.FindGameObjectsWithTag("FIX");
			foreach(GameObject obj in borns){
				if(obj.networkView.isMine){
					bornPosition = obj.transform.position;
				}
			}
			if(isServer){
				return Network.Instantiate (Resources.Load("prefab/" + cfg.codeToName(43)),
				                     bornPosition,
				                     Quaternion.identity,0
				                     ) ;
			}
			else{
				return Network.Instantiate (Resources.Load("prefab/" + cfg.codeToName(44)),
				                     bornPosition,
				                     Quaternion.Euler(0,0,180),0
				                     );
				
			}
		}
		// Update is called once per frame
		void Update () {
			int time = (int) Time.time;
			if(state == null){
				NetCtrl[] tanks = GameObject.FindObjectsOfType<NetCtrl>();
				foreach(NetCtrl obj in tanks){
					if(obj.networkView.isMine){
						state = obj.gameObject.GetComponent<NetPlayerState>();
						break;
					}	
				}

			}
			if(InitOK){

				if(myBase == null){
					Config.bases.Clear();
					Application.LoadLevel("gameover");

				}
				else if(enemyBase == null){
					Config.bases.Clear();
					Application.LoadLevel("win");
				}
			}

			// 刷兵
			if(time%genCD == 0&&!genLock){
				if(Network.isServer){
					if(time%2 == 0){
					Network.Instantiate(Resources.Load("prefab/enemy1_ai_p1"),serverGen[0], Quaternion.identity,0);
					}
					else{
					Network.Instantiate(Resources.Load("prefab/enemy1_ai_p1"),serverGen[1], Quaternion.identity,0);
					}
				}
				else{
					if(time%2 == 0){
					Network.Instantiate(Resources.Load("prefab/enemy1_ai_p2"),clientGen[0], Quaternion.identity,0);
					}
					else{
					Network.Instantiate(Resources.Load("prefab/enemy1_ai_p2"),clientGen[1], Quaternion.identity,0);
					}
				}
				genLock = true;
				ReLockAfterSec(1);
			}

		  	if(Config.bases.Count==2&&InitOK==false){
				
				InitOK = true;
				for(int i =0;i<Config.bases.Count;i++){

					if(((GameObject)Config.bases[i]).networkView.isMine){
						myBase = (GameObject)Config.bases[i];
					}
					else{
						enemyBase =(GameObject)Config.bases[i];
					}
				}
			}

			// 升级
			if (assetCount >= 100&&state.isAlive&&state.level<4) {
				// 显示升级按钮
				GameObject btnLevelup = GameObject.FindGameObjectWithTag ("LEVELUPBTN");
				btnLevelup.transform.localScale = new Vector3 (1, 1, 1);
			} else {
				// 隐藏按钮
				GameObject btnLevelup = GameObject.FindGameObjectWithTag ("LEVELUPBTN");
				btnLevelup.transform.localScale = new Vector3 (0, 0, 0);
			}
		}

		void OnGUI() {

			// 刷物资
			nowSec = (int)(Time.time - gameStartTime);
			if (lastSec < nowSec) {
				assetCount += 10;
				lastSec = nowSec;
			}
			//GUI.Label (new Rect (50, 21, 38, 20), assetCount + "", style);

			GUI.Label (new Rect (15,10, img.width, img.height), img);
			GUI.Label (new Rect (img.width+15,10, 300, img.height),assetCount + "", style);

		}
	
		
		// s秒后复活
		public void rebornAfterSec(float s) {

			StartCoroutine (reborn (s));
		}
		
		IEnumerator reborn(float s) {
			yield return new WaitForSeconds (s);
			
			//print (playerState.isImmune);
			Object obj = NewTank(Network.isServer,new Config());
			GameObject gameobj = (GameObject)obj;
			NetPlayerState playerState = gameobj.transform.GetComponent<NetPlayerState> ();
			playerState.isImmune = true;	// 无敌
			print ("复活");///
			playerState.isAlive = true;
		  	NetPlayerState.rebornTime = Time.time;
			if (Network.isClient) {
				gameobj.transform.GetComponent<NetCtrl> ().setReverseFactor (-1);
			}
			

			GameObject btn = GameObject.FindGameObjectWithTag("LEVELUPBTN");
			btn.transform.localScale = new Vector3(1,1,1);
		}

		public void ReLockAfterSec(float s) {
			StartCoroutine(relock (s));
		}
		
		IEnumerator relock(float s) {
			yield return new WaitForSeconds (s);
			genLock = false;
		}

		public void gameoverAfterSec(float s) {
			StartCoroutine (gameover (s));
		}
		
		IEnumerator gameover(float s) {
			yield return new WaitForSeconds (s);
			
			Application.LoadLevel("gameover");
		}

		void OnDestroy(){
			print ("netMain destroyed");
			Network.Disconnect();
		}
	}
}